package com.moli.lumpSugar.chatAi.handler;


import com.moli.lumpSugar.chatAi.dto.GPTRequestDTO;
import com.moli.lumpSugar.chatAi.properties.ChatAlYunProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Random;


@Slf4j
@Component
public class ChatAlYunHandler extends AbstractChatAIHandler {


    private static final List<String> ERROR_MSG = Arrays.asList(
            "还摸鱼呢？你不下班我还要下班呢。。。。",
            "没给钱，矿工了。。。。",
            "服务器被你们玩儿坏了。。。。",
            "你们这群人，我都不想理你们了。。。。",
            "艾特我那是另外的价钱。。。。",
            "得加钱");


    private static final Random RANDOM = new Random();

    private static String AI_NAME;

    @Autowired
    private ChatAlYunProperties chatAlYunProperties;

    private static String getErrorText() {
        int index = RANDOM.nextInt(ERROR_MSG.size());
        return ERROR_MSG.get(index);
    }

    @Override
    protected void init() {
        super.init();
        if (isUse()) {
            UserInfoResp userInfo = userService.getUserInfo(chatAlYunProperties.getAIUserId());
            if (userInfo == null) {
                log.error("根据AIUserId:{} 找不到用户信息", chatAlYunProperties.getAIUserId());
                throw new RuntimeException("根据AIUserId找不到用户信息");
            }
            if (StringUtils.isBlank(userInfo.getName())) {
                log.warn("根据AIUserId:{} 找到的用户信息没有name", chatAlYunProperties.getAIUserId());
                throw new RuntimeException("根据AIUserId: " + chatAlYunProperties.getAIUserId() + " 找到的用户没有名字");
            }
            AI_NAME = userInfo.getName();
        }
    }

    @Override
    protected boolean isUse() {
        return chatAlYunProperties.isUse();
    }

    @Override
    public Long getChatAIUserId() {
        return chatAlYunProperties.getAIUserId();
    }

    @Override
    protected String doChat(Message message) {
        String content = message.getContent().replace("@" + AI_NAME, "").trim();
        Long uid = message.getFromUid();
        try {
            return sendRequestToGPT(new GPTRequestDTO(content, uid));
        } catch (Throwable e) {
            return "退下吧，迷糊了~~";
        }
    }

    /**
     *
     * @param gptRequestDTO
     * @return
     */
    @Nullable
    private String sendRequestToGPT(GPTRequestDTO gptRequestDTO) {
        String content = gptRequestDTO.getContent();
        String text;
        try {
            Generation gen = new Generation();
            com.alibaba.dashscope.common.Message systemMsg = com.alibaba.dashscope.common.Message.builder()
                    .role(Role.SYSTEM.getValue())
                    .content("You are a helpful assistant.")
                    .build();
            com.alibaba.dashscope.common.Message userMsg = com.alibaba.dashscope.common.Message.builder()
                    .role(Role.USER.getValue())
                    .content(content)
                    .build();
            GenerationParam param = GenerationParam.builder()
                    // 若没有配置环境变量，请用百炼API Key将下行替换为：.apiKey("sk-xxx")
                    .apiKey(chatAlYunProperties.getKey())
                    .model(chatAlYunProperties.getModelName())
                    .messages(Arrays.asList(systemMsg, userMsg))
                    .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                    .build();
            GenerationResult call = gen.call(param);
            return call.getOutput().getChoices().get(0).getMessage().getContent();
        } catch (Exception e) {
            log.warn("gpt doChat warn:", e);
            text = "我累了，明天再聊吧";
        }
        return text;
    }

    @Override
    protected boolean supports(Message message) {
        if (!chatAlYunProperties.isUse()) {
            return false;
        }
        /* 前端传@信息后取消注释 */
        MessageExtra extra = message.getExtra();
        if (extra == null) {
            return false;
        }
        if (CollectionUtils.isEmpty(extra.getAtUidList())) {
            return false;
        }
        if (!extra.getAtUidList().contains(chatAlYunProperties.getAIUserId())) {
            return false;
        }

        if (StringUtils.isBlank(message.getContent())) {
            return false;
        }
        return StringUtils.contains(message.getContent(), "@" + AI_NAME)
                && StringUtils.isNotBlank(message.getContent().replace(AI_NAME, "").trim());
    }
}
